import { Buffer } from 'node:buffer'
import { randomBytes } from 'node:crypto'
import fs from 'node:fs'
import http from 'node:http'
import https from 'node:https'
import path from 'node:path'

export function readFileBuffer(filePath: string, cb: (arg: IFile) => void) {
  fs.readFile(filePath, (err, buffer) => {
    if (err)
      throw err
    cb && cb({ buffer, path: filePath })
  })
}

interface IFile {
  buffer: any
  path: string
}
interface UploadConfig {
  file: IFile // Buffer<ArrayBufferLike>
  name?: string
  headers?: Record<string, string>
  formData?: Record<string, string>
}
// 创建上传请求
export function uploadFile(url: string, { file = {} as IFile, name = 'file', headers = {}, formData = {} } = {} as UploadConfig) {
  const { buffer, path: filePath } = file
  const boundary = randomBytes(16).toString('hex')
  const delimiter = `--${boundary}`
  const endDelimiter = `${delimiter}--`

  // 构建自定义字段部分
  const fieldsParts = Object.entries(formData).map(([key, value]) => [
    `${delimiter}`,
    `Content-Disposition: form-data; name="${key}"`,
    '',
    value,
  ].join('\r\n'))

  const filePart = [
    `${delimiter}`,
    `Content-Disposition: form-data; name="${name}"; filename="${path.basename(filePath)}"`,
    `Content-Type: image/${path.extname(filePath).slice(1)}`,
    '',
    buffer.toString('binary'),
  ].join('\r\n')

  // 构建完整的请求体
  const body = [
    ...fieldsParts,
    filePart,
    endDelimiter,
    '',
  ].join('\r\n')

  const options = {
    method: 'POST',
    headers: {
      'Content-Type': `multipart/form-data; boundary=${boundary}`,
      'Content-Length': Buffer.byteLength(body, 'binary'),
      ...headers,
    },
  }
  const protocol = url.startsWith('https') ? https : http
  return new Promise((resolve, reject) => {
    const req = protocol.request(url, options, (res) => {
      let data = ''

      res.on('data', (chunk) => {
        data += chunk
      })

      res.on('end', () => {
        try {
          const body = JSON.parse(data)
          resolve(body)
        }
        catch (error) {
          resolve(data)
        }
      })
    })

    req.on('error', (error) => {
      reject(error)
    })
    // 写入请求体
    req.write(body, 'binary')
    req.end()
  })
}

export function isImageAccessible(url: string) {
  return new Promise((resolve, reject) => {
    const protocol = url.startsWith('https') ? https : http
    protocol.get(url, (res: http.IncomingMessage) => {
      // 检查响应状态码
      const code = Number(res.statusCode)
      if (code >= 200 && code < 300) {
        // 检查 Content-Type 是否为图片类型
        const contentType = res.headers['content-type']
        if (contentType && contentType.startsWith('image/')) {
          resolve(true)
        }
        else {
          resolve(false)
        }
      }
      else {
        resolve(false)
      }
    }).on('error', reject)
  })
}

// 示例调用
const imageUrl = 'https://master-sary-dev.oss-cn-wulanchabu.aliyuncs.com/cert/2024/10/09/49fd46ccbc6745c0a3e4636043849c9f.jpg' // 'http://example.com/path/to/image.jpg'

// isImageAccessible(imageUrl)
//   .then((accessible) => {
//     if (accessible) {
//       console.log('图片可访问')
//     } else {
//       console.log('图片不可访问')
//     }
//   })
//   .catch((error) => {
//     console.error('请求错误:', error)
//   })
